import { NextRequest, NextResponse } from 'next/server';
import { getDb } from '@/lib/db';

interface ChatMessage { role: 'user' | 'assistant' | 'system'; content: string; }

export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);
    const sessionId = searchParams.get('sessionId') || 'default';
    const page = parseInt(searchParams.get('page') || '1');
    const pageSize = parseInt(searchParams.get('pageSize') || '20');
    
    const db = await getDb();
    
    // 获取总数
    const countRes = await db.count('chat_messages', { sessionId });
    const total = countRes.success ? countRes.data || 0 : 0;
    
    // 获取分页数据
    const res = await db.findMany<any>(
      'chat_messages', 
      { sessionId }, 
      { 
        sortBy: 'createdAt', 
        sortOrder: 'desc', // 最新的在前
        page, 
        pageSize 
      }
    );
    
    return NextResponse.json({ 
      success: true, 
      data: res.data || [], 
      pagination: {
        page,
        pageSize,
        total,
        totalPages: Math.ceil(total / pageSize)
      }
    });
  } catch (e: any) {
    return NextResponse.json({ success: false, error: e?.message || 'DB error' }, { status: 500 });
  }
}

export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const { sessionId = 'default', messages } = body as { sessionId?: string; messages: ChatMessage[] };
    if (!messages || !Array.isArray(messages)) {
      return NextResponse.json({ success: false, error: 'messages 必须为数组' }, { status: 400 });
    }
    const now = new Date().toISOString();
    const rows = messages.map((m) => ({ ...m, sessionId, createdAt: now }));
    const db = await getDb();
    const res = await db.createMany<any>('chat_messages', rows);
    return NextResponse.json(res);
  } catch (e: any) {
    return NextResponse.json({ success: false, error: e?.message || 'DB error' }, { status: 500 });
  }
}